Using Puppeteer to test your web pages

hmm…. this article is not specific for SharePoint. It is because Puppeteer can be used to test against any web page, including SharePoint pages.

Puppeteer is a node library allow you script your web requests and capture the responses through programming. Here I provide sample for my SharePoint environment.

I am using Win10 with NodeJS installed (v12.13.0). My windows ID is able to browse SharePoint site directly (thru NTLM). To install Puppeteer, in your Node command prompt, type:

npm i puppeteer

above command will download latest Puppeteer from Internet and install on your PC. Note that a recent version of Chromium will be downloaded and installed in the same way. Chromium is essential for Puppeteer. If your environment is behind a firewall or proxy that block your download, you may need to troubleshooting for that unfortunately…

After install, you are now ready. You can directly copy my sample and save it as test.js.

const puppeteer = require(‘puppeteer’);

const siteurl = ‘https://mysharepoint.com/sites/test/’;

const urls = [
‘SitePages/Home.aspx’,
‘SitePages/Document.aspx’,
‘SitePages/Contact.aspx’,
‘SitePages/About.aspx’
];

(async () => {
const browser = await puppeteer.launch();

for (let i = 0; i < urls.length; i++) {
const url = siteurl+urls[i];
const page = await browser.newPage();
await page.setViewport({
width: 800,
height: 1200,
deviceScaleFactor: 1,
});
page.on(‘console’, msg => console.log(url+’ Console:’, msg.text()));
page.on(‘pageerror’, error => {console.log(error.message);});
//page.on(‘response’, response => {console.log(response.status(), response.url());});
//page.on(‘requestfailed’, request => {console.log(request.failure().errorText, request.url());});

await page.goto(`${url}`, {waitUntil: ‘networkidle2’});
await page.screenshot({path: i + ‘.png’});
}

await browser.close();
})();

Above script will loop thru each URL in the array urls, browse each url, capture the response (it will be shown in your command prompt) and captured a screen capture (size 800 x 1200px) saved in the same directory.

To run above script, simply type follow command:

node test.js

  • Using a larger height parameter if your webpage require scroll down to see the full picture.
  • waitUntil: ‘networkidle2’ means the web request will be wait until network traffic is idle to start the next request.
  • console.log(response.status(), response.url()) will capture the response status code (e.g. 200, 302, 404) with the URL.

In case your PC is sitting behind a proxy,  update the script for this part:

(async () => {
const browser = await puppeteer.launch({
args: [
‘–proxy-server=proxy.server.hk:8080’,
// Use proxy for localhost URLs
‘–proxy-bypass-list=<-loopback>’,
]
});

Enjoy!

發表留言